package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	router := gin.Default()
	router.POST("/upload", func(c *gin.Context) {
		file, err := c.FormFile("testFile")
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 500, "msg": err.Error(), "data": nil})
			return
		}
		// file.Size单位是字节
		fmt.Printf("fileName: %s, fileSize: %.1fkb\n", file.Filename, float64(file.Size)/1024)
		//err = SaveFile(c, 0, file, fmt.Sprintf("./src/03_gin/08_file_upload/upload/%s", file.Filename))
		err = SaveFile(c, 1, file, fmt.Sprintf("./src/03_gin/08_file_upload/upload/%s", file.Filename))
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 500, "msg": err.Error(), "data": nil})
			return
		}
		c.JSON(http.StatusOK, gin.H{"msg": "success", "code": 200, "data": nil})
	})
	router.POST("/multiUpload", func(c *gin.Context) {
		form, err := c.MultipartForm()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 500, "msg": err.Error(), "data": nil})
			return
		}
		for _, file := range form.File["uploads"] {
			err = SaveFile(c, 0, file, fmt.Sprintf("./src/03_gin/08_file_upload/multiUpload/%s", file.Filename))
		}
		c.JSON(http.StatusOK, gin.H{"msg": "success", "code": 200, "data": nil})
	})
	router.Run(":8080")
}

func SaveFile(c *gin.Context, saveType int, file *multipart.FileHeader, filePath string) error {
	switch saveType {
	case 0:
		return c.SaveUploadedFile(file, filePath)
	case 1:
		reader, err := file.Open()
		if err != nil {
			return err
		}
		defer reader.Close()
		writer, err := os.Create(filePath)
		if err != nil {
			return err
		}
		defer writer.Close()
		n, err := io.Copy(writer, reader)
		if err != nil {
			return err
		}
		fmt.Println("复制了：", n, "个字节")
	}
	return nil
}
